package com.yege.lab.user;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yege
 */
@Service
public class UserService {
    private final static Log log = LogFactory.getLog(UserService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private EmailPulsarProducer emailPulsarProducer;

    /**
     * 注册用户
     * @param email
     * @param name
     * @param pwd
     * @param activeCode
     */
    public void registerUser(String email,String name,String pwd,String activeCode)throws Exception{
        jdbcTemplate.update("insert into t_user(email,name,pwd,active_code) values(?,?,?,?)",email,name,pwd,activeCode);
        String msg=email+","+activeCode;
        emailPulsarProducer.sendMsg(msg);
        //发送消息到消息队列

    }

    /**
     * 激活用户
     * @param activeCode
     */
    public int activeUser(String activeCode)throws Exception{
        int result=jdbcTemplate.update("update t_user set active=1 where active_code=?",activeCode);
        return result;
    }

    /**
     * 用户登录
     * @param email
     * @param pwd
     */
    public String userLogin(String email,String pwd)throws Exception{
        Map<String,Object> user =jdbcTemplate.queryForMap("select email,name,'' pwd,'' activeCode from t_user where email=? and pwd=?",email,pwd);
        return user.get("name").toString();

    }

    /**
     * 用户列表
     */
    public List<UserDto> userList()throws Exception{
        List<Map<String,Object>> UserDtos =jdbcTemplate.queryForList("select email,name,'' pwd,active,'' activeCode from t_user order by id");
        List<UserDto> userDtos=new ArrayList<>();
        for(Map<String,Object> m:UserDtos){
            Integer active= (Integer) m.get("active");
            UserDto userDto=new UserDto(m.get("email").toString(),
                                        m.get("name").toString(),
                                        m.get("pwd").toString(),
                                        m.get("activeCode").toString(),
                                        active
            );
            userDtos.add(userDto);
        }
        return userDtos;

    }
}
